import Vue from 'vue';
import {
  Message
} from 'element-ui';

const BASE_URL = 'http://localhost:354/api';

function getQueryString(params) {
  return `?${Object.keys(params).map(key => `${key}=${params[key]}`).join('&')}`;
}

// 公共请求方法
async function request(url, method, data, isShowSuccessInfo = false, isShowErrorInfo = true, {
  params,
  options
} = {}) {
  // 统一请求方法的大小写，防止判断不全
  method = method.toString().toLowerCase();
  // 合并初始请求设置和传入的设置参数
  options = Object.assign({
    method,
    credentials: 'include',
    headers: new Headers({
      'Content-Type': 'application/json',
      'Authorization': sessionStorage.getItem('token')
    })
  }, options);
  // get方式会将data作为参数进行请求，否则正常传递data
  if (method === 'get') {
    params = data;
  } else {
    options.body = JSON.stringify(data);
  }
  // 拼接前置请求地址
  url = `${BASE_URL}${url}`;
  // 拼接请求参数
  params && (url += getQueryString(params));
  // 展开两层promise
  const pm = await fetch(url, options);
  const res = await pm.json();
  // 根据参数判断是否显示提示
  if (res.meta.status !== 200 && isShowErrorInfo) {
    Message.error(res.meta.msg);
  } else if (res.meta.status === 200 && isShowSuccessInfo) {
    Message.success(res.meta.msg);
  }
  return res.data;
}

const methods = ['get', 'post', 'put', 'delete'];
let http = {};
methods.forEach(m => http[m] = (url, data, isShowSuccessInfo = false, isShowErrorInfo = true, options) => request(url, m, data, isShowSuccessInfo, isShowErrorInfo, options));

Vue.prototype.$http = http;

// 将接口暴露出去，提供在非vue页面中的请求方法
export default http;
